package com.currency.common.web.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.currency.common.constant.SecurityConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @author Lan
 * @date 2021/12/14
 */
@Slf4j
public class JwtUtils {

    @SneakyThrows
    public static JSONObject getJwtPayload() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String payload = request.getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
        if (null == payload) {
            throw new Exception("请传入认证头");
        }
        return JSONUtil.parseObj(URLDecoder.decode(payload, StandardCharsets.UTF_8.name()));
    }

    /**
     * 解析JWT获取用户ID
     *
     * @return
     */
    public static Long getUserId() {
        return getJwtPayload().getLong(SecurityConstants.USER_ID_KEY);
    }

    /**
     * 解析JWT获取获取用户名
     * @return
     */
    public static String getUsername() {
        return getJwtPayload().getStr(SecurityConstants.USER_NAME_KEY);
    }



    /**
     * JWT获取用户角色列表
     *
     * @return 角色列表
     */
    public static List<String> getRoles() {
        List<String> roles = null;
        JSONObject payload = getJwtPayload();
        if (payload.containsKey(SecurityConstants.JWT_AUTHORITIES_KEY)) {
            roles = payload.getJSONArray(SecurityConstants.JWT_AUTHORITIES_KEY).toList(String.class);
        }
        return roles;
    }
}
